<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class DBManageCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:backup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'DBManageCommand: description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if (function_exists('exec')) {
            $this->info('=> check function [exec] ok.');
        } else {
            $this->info('=> function [exec] not found.');
        }
        $dbName = config('database.connections.mysql.database');
        $dbUsername = config('database.connections.mysql.username');
        $dbPassword = config('database.connections.mysql.password');

        // $fileName = date('Ymd_His').'_'.$dbName.".sql";
        $fileName = date('Ymd').'_'.$dbName.".sql";
        $dumpFileName = storage_path("backup/".$fileName);

        // mysqldump -uroot -pPassword [database name] > [dump file]
        // mysql [database name] < [backup file name]
        try{
            $this->info('=> check mysqldump ...');
            $result = exec('which mysqldump');
            if (empty($result)) {
                $this->info('=> [mysql] not found.');
            }

            if(! is_dir(dirname($dumpFileName))){
                $this->info('=> [Directory nonexistent] ' . dirname($dumpFileName));
            }

            $this->info('=> [OK] Start to backuping database ['.$dbName.'].');
            $result = exec($result ." -u{$dbUsername} -p{$dbPassword} {$dbName} > {$dumpFileName}");
            if (empty($result)) {
                $this->info('=> [OK] See ['.$dumpFileName.'].');
                $this->info('=> [OK] Finish.');
            } else {
                var_dump($result);
            }

        } catch(\Exception $e) {
            var_dump($e->getMessage());
        }

    }
}
